<template>
    <div>
        <Card shadow>
            <div class="search-con search-con-top">
                <ButtonGroup>
                    <Button   class="search-btn" type="primary" @click="handleModal()">
                        <span>添加</span>
                    </Button>
                </ButtonGroup>
            </div>
            <Table :columns="columns" :data="data" :loading="loading">
                <template slot="action" slot-scope="{ row }">
                    <a :disabled="hasAuthority('TenantEdit')?false:true"   @click="handleModal(row)">
                        编辑</a>&nbsp;
                    <Dropdown v-show="hasAuthority('TenantEdit')" transfer ref="dropdown" @on-click="handleClick($event,row)">
                        <a href="javascript:void(0)">
                            <span>更多</span>
                            <Icon type="ios-arrow-down"></Icon>
                        </a>
                        <DropdownMenu slot="list">
                            <DropdownItem  name="remove">删除</DropdownItem>
                        </DropdownMenu>
                    </Dropdown>&nbsp;
                </template>
            </Table>
            <Page :total="pageInfo.total" :current="pageInfo.page" :page-size="pageInfo.limit" show-elevator show-sizer
                  show-total
                  @on-change="handlePage" @on-page-size-change='handlePageSize'></Page>
        </Card>
        <Modal v-model="modalVisible"
               :title="modalTitle"
               width="40"
               @on-cancel="handleReset">
            <div>
              <Tabs @on-click="handleTabClick" :value="current">
                <TabPane label="租户信息" name="form1">
                <Form ref="form" :model="formItem" :rules="formItemRules" :label-width="100">
                    <FormItem label="租户编码" prop="tenantId">
                        <Input v-model="formItem.tenantId"  placeholder="请输入内容"></Input>
                    </FormItem>
                    <FormItem label="租户名称" prop="tenantName">
                        <Input v-model="formItem.tenantName"  placeholder="请输入内容"></Input>
                    </FormItem>
                    <FormItem label="联系人" prop="linkman">
                        <Input v-model="formItem.linkman"  placeholder="请输入内容"></Input>
                    </FormItem>
                    <FormItem label="联系电话" prop="contactNumber">
                        <Input v-model="formItem.contactNumber"  placeholder="请输入内容"></Input>
                    </FormItem>
                    <FormItem label="专票税费率(%)" prop="speciaTaxRate">
                        <Input v-model="formItem.speciaTaxRate"  placeholder="请输入内容"></Input>
                    </FormItem>
                    <FormItem label="服务费率(%)" prop="serviceRate">
                        <Input v-model="formItem.serviceRate"  placeholder="请输入内容"></Input>
                    </FormItem>
                    <FormItem label="联系地址" prop="address">
                        <Input v-model="formItem.address"  placeholder="请输入内容"></Input>
                    </FormItem>
                    <FormItem label="创建人" prop="createUser">
                        <Input v-model="formItem.createUser"  placeholder="请输入内容"></Input>
                    </FormItem>
                    <FormItem label="修改人" prop="updateUser">
                        <Input v-model="formItem.updateUser"  placeholder="请输入内容"></Input>
                    </FormItem>
                    <FormItem label="状态" prop="status">
                        <Input v-model="formItem.status"  placeholder="请输入内容"></Input>
                    </FormItem>

                </Form>
                </TabPane>
                <TabPane :disabled="!formItem.tenantId" label="分配角色" name="form2">
                  <Form v-show="current == 'form2'" ref="form2" :model="formItem" :label-width="100" :rules="formItemRules">
                    <FormItem label="分配角色" prop="grantRoles">
                      <CheckboxGroup v-model="formItem.grantRoles">
                        <Checkbox v-for="item in selectRoles" :label="item.roleId"><span>{{ item.roleName }}</span></Checkbox>
                      </CheckboxGroup>
                    </FormItem>
                  </Form>
                </TabPane>
                <TabPane :disabled="!formItem.tenantId" label="分配权限" name="form3">
                  <Alert type="info" show-icon>
                    支持租户单独分配功能权限<code>(除角色已经分配菜单功能,禁止勾选!)</code></Alert>
                  <Form v-show="current == 'form3'" ref="form3" :model="formItem" :rules="formItemRules" :label-width="100">
                    <FormItem label="过期时间" prop="expireTime">
                      <Badge v-if="formItem.isExpired" text="授权已过期">
                        <DatePicker v-model="formItem.expireTime" class="ivu-form-item-error" type="datetime"
                                    placeholder="设置有效期"></DatePicker>
                      </Badge>
                      <DatePicker v-else="" v-model="formItem.expireTime" type="datetime" placeholder="设置有效期"></DatePicker>
                    </FormItem>
                    <FormItem label="功能菜单" prop="grantMenus">
                      <tree-table
                        ref="tree"
                        style="max-height:450px;overflow: auto"
                        expand-key="menuName"
                        :expand-type="false"
                        :is-fold="false"
                        :tree-type="true"
                        :selectable="true"
                        :columns="columns2"
                        :data="selectMenus">
                        <template slot="operation" slot-scope="scope">
                          <CheckboxGroup v-model="formItem.grantActions">
                            <Checkbox :disabled="item.disabled" v-for="item in scope.row.actionList" :label="item.authorityId">
                              <span :title="item.actionDesc">{{item.actionName}}</span>
                            </Checkbox>
                          </CheckboxGroup>
                        </template>
                      </tree-table>
                    </FormItem>
                  </Form>
                </TabPane>
              </Tabs>
                <div class="drawer-footer">
                    <Button type="default" @click="handleReset">取消</Button>&nbsp;
                    <Button type="primary" @click="handleSubmit" :loading="saving">保存</Button>
                </div>
            </div>
        </Modal>
    </div>
</template>

<script>
    import Tenant from '@/api/tenant'
    import {getAllRoles} from '@/api/role'
    import {startWith, listConvertTree} from '@/libs/util'
    import {
      getAuthorityMenu,
      getAuthorityUser,
      grantAuthorityUser
    } from '@/api/authority'
    export default {
        name: 'Tenant',
        data () {
            return {
                loading: false,
                saving: false,
                modalVisible: false,
                modalTitle: '',
                pageInfo: {
                    total: 0,
                    page: 1,
                    limit: 10
                },
              current: 'form1',
              forms: [
                'form1',
                'form2',
                'form3'
              ],
              selectMenus: [],
              selectRoles: [],
                formItemRules: {

                    tenantName: [
                        {required: true, message: '租户名称不能为空', trigger: 'blur'}
                    ],


                },
                formItem: {
                    id: '',
                    tenantId: '',
                    tenantName: '',
                    linkman: '',
                    contactNumber: '',
                    speciaTaxRate: '',
                    serviceRate: '',
                    address: '',
                    createUser: '',
                    updateUser: '',
                    status: '',
                    isDeleted: '',
                    type: '',
                    grantRoles: [],
                    grantActions: [],
                    grantMenus: [],
                    expireTime: '',
                    isExpired: false
                },
                columns: [

                    {
                        title: '租户名称',
                        key: 'tenantName',
                        width: 100
                    },
                    {
                        title: '联系人',
                        key: 'linkman',
                        width: 100
                    },
                    {
                        title: '联系电话',
                        key: 'contactNumber',
                        width: 100
                    },
                    {
                        title: '专票税费率(%)',
                        key: 'speciaTaxRate',
                        width: 100
                    },
                    {
                        title: '服务费率(%)',
                        key: 'serviceRate',
                        width: 100
                    },
                    {
                        title: '联系地址',
                        key: 'address',
                        width: 100
                    },
                    {
                        title: '创建人',
                        key: 'createUser',
                        width: 100
                    },
                    {
                        title: '修改人',
                        key: 'updateUser',
                        width: 100
                    },
                    {
                        title: '状态',
                        key: 'status',
                        width: 100
                    },
                    {
                        title: '是否已删除',
                        key: 'isDeleted',
                        width: 100
                    },

                    {
                        title: '操作',
                        slot: 'action',
                        fixed: 'right',
                        width: 120
                    }
                ],
                columns2: [
                  {
                    title: '菜单',
                    key: 'menuName',
                    minWidth: '250px',
                  },
                  {
                    title: '操作',
                    type: 'template',
                    template: 'operation',
                    minWidth: '200px'
                  }
                ],
                data: []
            }
        },
        methods: {
            handleModal (data) {
              if (data) {
                this.formItem = Object.assign({}, this.formItem, data)
              }
              if (this.current === this.forms[0]) {
                this.modalTitle = data ? '编辑租户 - ' + data.tenantName : '添加租户'
                this.modalVisible = true
              }
              if (this.current === this.forms[1]) {
                this.modalTitle = data ? '分配角色 - ' + data.tenantName : '分配角色'
                this.handleLoadRoles(this.formItem.tenantId)
              }
              if (this.current === this.forms[3]) {
                this.modalTitle = data ? '分配权限 - ' + data.tenantName : '分配权限'
                this.handleLoadUserGranted(this.formItem.tenantId)
              }
                if (data) {
                    this.modalTitle = '编辑租户表'
                    this.formItem = Object.assign({}, this.formItem, data)
                } else {
                    this.modalTitle = '添加租户表'
                }
                this.modalVisible = true
            },
            handleReset () {
                const newData = {
                    id: '',
                    tenantId: '',
                    tenantName: '',
                    linkman: '',
                    contactNumber: '',
                    speciaTaxRate: '',
                    serviceRate: '',
                    address: '',
                    createUser: '',
                    updateUser: '',
                    status: '',
                    isDeleted: '',
                    type: '',
                }
                this.formItem = newData
                //重置验证
               // let form  = this.$refs['form']
              //重置验证
              this.forms.map(form => {
                this.handleResetForm(form)
              })
              this.current = this.forms[0]
              this.formItem.grantMenus = []
              this.formItem.grantActions = []
              this.modalVisible = false

                this.saving = false
            },
          handleResetForm(form) {
           // this.$refs[form].resetFields()
          },
            handleSubmit () {
              if (this.current === this.forms[0]) {
                let form = this.$refs['form']
                form.validate((valid) => {
                  if (valid) {
                    this.saving = true
                    if (this.formItem.id) {
                      Tenant.update(this.formItem).then(res => {
                        if (res.code === 0) {
                          this.$Message.success('保存成功')
                          this.handleReset()
                        }
                        this.handleSearch()
                      }).finally(() => {
                        this.saving = false
                      })
                    } else {
                      Tenant.add(this.formItem).then(res => {
                        this.handleReset()
                        this.handleSearch()
                        if (res.code === 0) {
                          this.$Message.success('保存成功')
                        }
                      }).finally(() => {
                        this.saving = false
                      })
                    }
                  }
                })
              }
              //添加租户角色
              if (this.current === this.forms[1] && this.formItem.tenantId) {
                this.$refs[this.current].validate((valid) => {
                    if (valid) {
                      this.saving = true
                      Tenant.addTenantRoles(this.formItem).then(res => {
                      if (res.code === 0) {
                      this.$Message.success('分配角色成功')
                      this.handleReset()
                      }
                      this.handleSearch()
                      }).finally(() => {
                        this.saving = false
                      })
                    }
               })
              }

            },
          getCheckedAuthorities() {
            const menus = this.$refs['tree'].getCheckedProp('authorityId')
              return menus.concat(this.formItem.grantActions)
          },
          handleLoadRoles(tenantId) {
            if (!tenantId) {
              return
            }
            const that = this
            const p1 = getAllRoles()
            const p2 = Tenant.getTenantRoles(tenantId)
            Promise.all([p1, p2]).then(function (values) {
              let res1 = values[0]
              let res2 = values[1]
              if (res1.code === 0) {
                that.selectRoles = res1.data
              }
              if (res2.code === 0) {
                let result = []
                res2.data.map(item => {
                  result.push(item.roleId)
                })
                that.formItem.grantRoles = result
              }
              that.modalVisible = true
            })
          },
          handleLoadUserGranted(userId) {
            const that = this
            const p1 = getAuthorityMenu()
            console.info(p1);
            const p2 = getAuthorityUser(userId)
            const roleAuthorites = []
            Promise.all([p1, p2]).then(function (values) {
              let res1 = values[0]
              let res2 = values[1]
              if (res1.code === 0 && res1.data) {
                let opt = {
                  primaryKey: 'menuId',
                  parentKey: 'parentId',
                  startPid: '0'
                }
                if (res2.code === 0 && res2.data && res2.data.length > 0) {
                  let menus = []
                  let actions = []
                  res2.data.map(item => {
                    if(item.owner === 'role'){
                      roleAuthorites.push(item.authorityId);
                    }
                    // 菜单权限
                    if (item.authority.indexOf('MENU_') != -1 && !menus.includes(item.authorityId)) {
                      menus.push(item.authorityId)
                    }
                    // 操作权限
                    if (item.authority.indexOf('ACTION_') != -1 && !actions.includes(item.authorityId)) {
                      actions.push(item.authorityId)
                    }
                  })
                  that.formItem.grantMenus = menus;
                  that.formItem.grantActions = actions;
                  // 时间
                  if (res2.data.length > 0) {
                    that.formItem.expireTime = res2.data[0].expireTime
                    that.formItem.isExpired = res2.data[0].isExpired
                  }
                }
                res1.data.map(item => {
                  // 菜单选中
                  if (that.formItem.grantMenus.includes(item.authorityId)) {
                    item._isChecked = true
                    // 归属角色权限,禁止授权
                    if(roleAuthorites.includes(item.authorityId)){
                      // 插件不支持,禁用
                      item.disabled = true
                      item.menuName += ' (禁止勾选)'
                    }
                  }

                  // 功能权限
                  item.actionList.map(action => {
                    if(roleAuthorites.includes(action.authorityId)){
                      action.disabled = true
                    }
                  })
                })
                that.selectMenus = listConvertTree(res1.data, opt)
              }
              that.modalVisible = true
            })
          },
            handleSearch (page) {
                if (page) {
                    this.pageInfo.page = page
                }
                this.loading = true
                Tenant.list({page: this.pageInfo.page, limit: this.pageInfo.limit}).then(res => {
                    this.data = res.data.records
                    this.pageInfo.total = parseInt(res.data.total)
                }).finally(() => {this.loading = false})
            },
            handlePage (current) {
                this.pageInfo.page = current
                this.handleSearch()
            },
            handlePageSize (size) {
                this.pageInfo.limit = size
                this.handleSearch()
            },
            handleRemove (data) {
               let modal = this.$Modal
               modal.confirm({
                    title: '确定删除吗？',
                    onOk: () => {
                        Tenant.remove(data.id).then(res => {
                            if (res.code === 0) {
                                this.pageInfo.page = 1;
                                this.$Message.success('删除成功');
                            }
                            this.handleSearch();
                        })
                    }
                })
            },
            handleClick (name, row) {
                switch (name) {
                    case 'remove':
                        this.handleRemove(row)
                        break
                }
            },
          handleTabClick(name){
            this.current = name
            this.handleModal();
          }
        },
        mounted: function () {
            this.handleSearch()
        }
    }
</script>
